﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace HexTo4_3
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: FastaTo4_3 <fasta file>");
                return;
            }
            try
            {
                string hexFile = args[0];

                FileAttributes attr = File.GetAttributes(hexFile);
                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    List<string> files = new List<string>(Directory.EnumerateFiles(hexFile, "*.hex", SearchOption.AllDirectories).OrderBy(n=>n));
                    foreach (string f in files)
                    {
                        string fourThirdFile = ProperFileName(f);
                        if(File.Exists(fourThirdFile)){
                            Console.WriteLine("Skip " + fourThirdFile);
                        } else {
                            Console.WriteLine("Start " + fourThirdFile);
                            string res = Make4_3(f, fourThirdFile);
                            Console.WriteLine(res + " " + fourThirdFile);
                        }
                    }
                }
                else { 
                    
                    string fourThirdFile = ProperFileName(hexFile);
                    string res = Make4_3(hexFile, fourThirdFile);
                    Console.WriteLine(res + " " + fourThirdFile);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }

        private static string Make4_3(string hexFile, string fourThirdFile)
        {
            string res = "Success";

            if (!File.Exists(hexFile))
            {
                return "File not found: " + hexFile;
            }

            DigitalGenetics.SumMatrix.HexTo4_3(hexFile, fourThirdFile);

            return res;
        }

        private static string ProperFileName(string partName)
        {
            string currFolder = Path.GetDirectoryName(partName);

            string fileName = Path.GetFileName(partName);
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(c, '_');
            }
            fileName = Path.Combine(currFolder, fileName + ".4_3");
            return fileName;
        }

    }
}
